var mysql = require('mysql');
var User = {};
var connection = mysql.createConnection({
    host: 'localhost',
    port: '3307',
    user: 'root',
    password: '123456',
    database: 'nodejs'
});

connection.connect();

// 创建用户表（如果不存在）
User.createTable = function (callback) {
    const createTableSql = `
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            username VARCHAR(255) NOT NULL,
            password VARCHAR(255) NOT NULL
        )
    `;
    connection.query(createTableSql, function (err, result) {
        if (err) {
            console.log('[CREATE TABLE ERROR] - ', err.message);
            return callback(err);
        }
        callback(null, result);
    });
};

User.register = function (user, callback) {
    const addUserSql = 'INSERT INTO users (username, password) VALUES (?,?)';
    const addUserParams = [user.username, user.password];
    connection.query(addUserSql, addUserParams, function (err, result) {
        if (err) {
            console.log('[REGISTER ERROR] - ', err.message);
            return callback(err);
        }
        callback(null, result);
    });
};

User.login = function (username, password, callback) {
    const loginSql = 'SELECT * FROM users WHERE username =? AND password =?';
    const loginParams = [username, password];
    connection.query(loginSql, loginParams, function (err, result) {
        if (err) {
            console.log('[LOGIN ERROR] - ', err.message);
            return callback(err);
        }
        callback(null, result.length > 0);
    });
};

module.exports = User;